import { defineStore } from "pinia";
import { http, interfaceUrl, imgUrl } from "@/utils/http";
import url from "./url";
import map from "./map";
import { PoiInfo, PositionInfo, poiTypeInterface } from "@/utils/type";
import { marker, navi } from "..";
import { detailsObj } from "@/components/details/Details";
import { vmapObj } from "@/components/vmap/Vmap";
import { searchObj } from "../../components/search/Search";
import { routeObj } from "@/components/route/Route";

import icon1 from "@/assets/img/menu/book.png";
import icon2 from "@/assets/img/menu/public.png";
import icon3 from "@/assets/img/menu/read.png";
import icon4 from "@/assets/img/menu/sevice.png";

const usePoiStore = defineStore("poi", {
  state: () => ({
    info: {} as PoiInfo,
    infoType: "details" as "details" | "choice" | "",
    start: {} as PoiInfo, //起点POI的点位
    end: {} as PoiInfo, //终点POI的点位
    now: {} as PoiInfo, //当前POI的点位
    type: "end" as "end" | "start",
    typeList: [] as poiTypeInterface[],
    poiList: [] as PoiInfo[], //所有楼层的list
  }),
  getters: {},
  actions: {
    setNowPoi(curPosition: PositionInfo, name?: string) {
      if (curPosition.x !== 0) {
        this.now = {
          poiName: name ? name : "当前位置",
          fid: "999",
          floorId: curPosition.floorId,
          coordinateX: curPosition.x,
          coordinateY: curPosition.y,
        };
      }
    },
    setStartPoi(curPosition: PositionInfo) {
      if (curPosition.x !== 0) {
        this.start = {
          poiName: "开始位置",
          fid: "999",
          floorId: curPosition.floorId,
          coordinateX: curPosition.x,
          coordinateY: curPosition.y,
        };
      }
    },
    setEndPoi(curPosition: PositionInfo) {
      if (curPosition.x !== 0) {
        this.end = {
          poiName: "结束位置",
          fid: "999",
          floorId: curPosition.floorId,
          coordinateX: curPosition.x,
          coordinateY: curPosition.y,
        };
      }
    },
    requestPoiInfo(fid: number, targets?: any) {
      //获取POI信息 -  接口(fid查询)
      let httpUrl = interfaceUrl + "poi/detail?fid=" + fid;
      if (url.bookid.length > 1) {
        httpUrl = httpUrl + "&bookid=" + url.bookid;
      }
      http({
        url: httpUrl,
        method: "get",
        success: (res) => {
          console.log("requestPoiInfo", res, map.initModel);

          if (map.initModel) {
            map.initModel.resetColor();
          }
          if (res.data == null) {
            map.choiceFlag = false;
            map.detailsFlag = false;
            map.menuFlag = true;
          } else if (res.code == 1) {
            let data = res.data;

            if (data.bookInfo) {
              this.info.bookInfo = data.bookInfo;
              this.info.bookPlace = data.bookPlace;
            }
            this.info.categoryId = data.categoryId;
            this.info.fid = data.fid;
            this.info.floorId = data.floorId;
            this.info.areaId = data.areaId;
            this.info.poiName = data.poiName;
            this.info.poiIntro = data.poiIntro;
            this.info.poiDetail = data.poiDetail;
            this.info.poiType = data.poiType;
            this.info.poiStatus = data.poiStatus;
            this.info.poiIcon = data.poiIcon;
            this.info.poiImgMoblie = imgUrl + data.poiImgMoblie;
            this.info.poiImgPc = imgUrl + data.poiImgPc;
            this.info.coordinateX = +data.coordinateX;
            this.info.coordinateY = +data.coordinateY;
            this.info.distance = "";

            if (this.infoType == "details") {
              map.curPageType = "details";

              //展示poi详细信息弹框
              map.detailsFlag = true;
              map.menuFlag = false;
              map.listFlag = false;
              marker.removeImageMarker();

              //起点
              this.start = this.now;
              //终点
              this.end = this.info;

              //显示标记（终点）
              marker.setImageMarker(
                {
                  x: this.end.coordinateX,
                  y: this.end.coordinateY,
                  floorId: this.end.floorId,
                },
                true
              );
              if (targets) {
                var tar = targets;
                for (var i = 0; i < tar.length; i++) {
                  // @ts-ignore
                  if (tar[i].type == fengmap.FMType.MODEL) {
                    tar[i].setColor("#FF4040", 1);
                    map.initModel = tar[i];
                  }
                }
              }

              //TODO:智能书架数据赋值
              // localStorage.setItem("bookshelf", JSON.stringify(this.info));
              // console.log("detailsRef.value.setData(data)2");
            } else if (this.infoType == "choice") {
              this.now = this.info;
              map.menuFlag = false;
              map.choiceFlag = true;
            }
          }
        },
      });
    },
    requestPoiInfo2(fid: number) {
      let httpUrl = interfaceUrl + "poi/detail?fid=" + fid;
      let that = this;
      http({
        url: httpUrl,
        method: "get",
        success(res) {
          if (map.initModel) {
            map.initModel.resetColor();
          }
          if (res.data == null) {
            map.choiceFlag = false;
            map.detailsFlag = false;
            map.menuFlag = true;

            return;
          }
          if (res.code == 1) {
            let data = res.data;
            that.info.categoryId = data.categoryId;
            that.info.fid = data.fid;
            that.info.floorId = data.floorId;
            that.info.areaId = data.areaId;
            that.info.poiName = data.poiName;
            that.info.poiIntro = data.poiIntro;
            that.info.poiDetail = data.poiDetail;
            that.info.poiType = data.poiType;
            that.info.poiStatus = data.poiStatus;
            that.info.poiIcon = data.poiIcon;
            that.info.poiImgMoblie = imgUrl + data.poiImgMoblie;
            that.info.poiImgPc = imgUrl + data.poiImgPc;
            that.info.coordinateX = data.coordinateX;
            that.info.coordinateY = data.coordinateY;
            that.info.distance = "";
          }
        },
      });
    },
    getTestImg(index) {
      switch (index) {
        case 0:
          return icon1;
        case 1:
          return icon2;
        case 2:
          return icon3;
        case 3:
          return icon4;
      }
    },
    requestPoiTypeInfo() {
      // 获取poi分类信息
      let that = this;
      http({
        url: interfaceUrl + "category",
        method: "get",
        success(res) {
          console.log("requestPoiTypeInfo", res);
          if (res.code == 1) {
            let data = res.data.data;
            that.typeList = [];
            for (let i = 0; i < data.length; i++) {
              that.typeList.push({
                categoryId: data[i].categoryId,
                name: data[i].name,
                image: imgUrl + data[i].image,
                // image: `${that.getTestImg(i)}`,
                status: data[i].status,
              });
            }
            map.menuFlag = true;
          }
        },
      });
    },
    requestPoiList(categoryId: number) {
      let httpUrl = interfaceUrl + "poi?categoryId=" + categoryId;
      let that = this;
      http({
        url: httpUrl,
        method: "get",
        success(res) {
          if (res.code == 1) {
            let data = res.data.data;
            that.poiList = [];
            for (let i = 0; i < data.length; i++) {
              //计算距离
              let sp = {
                x: that.now.coordinateX,
                y: that.now.coordinateY,
              };

              let ep = { x: data[i].coordinateX, y: data[i].coordinateY };
              // @ts-ignore
              let dis = fengmap.FMCalculator.distance(sp, ep);
              that.poiList.push({
                //分类ID
                categoryId: data[i].categoryId,
                fid: data[i].fid,
                floorId: data[i].floorId - 1,
                areaId: data[i].areaId,
                poiName: data[i].poiName,
                poiIntro: data[i].poiIntro,
                poiDetail: data[i].poiDetail,
                poiType: data[i].poiType,
                poiStatus: data[i].poiStatus,
                poiIcon: data[i].poiIcon,
                poiImgMoblie: imgUrl + data[i].poiImgMoblie,
                poiImgPc: imgUrl + data[i].poiImgPc,
                //x坐标
                coordinateX: data[i].coordinateX,
                //y坐标
                coordinateY: data[i].coordinateY,
                //距离
                distance: dis.toFixed(0),
              });
            }

            console.log("requestPoiList", that.poiList);

            map.curPageType = "list";
            map.menuFlag = false;
            map.listFlag = true;
          }
        },
      });
    },
    requestPoiList2(kind: string, keyword: string) {
      //获取POILIST信息 -  接口(keyword查询)
      let httpUrl = interfaceUrl + "poi?keyword=" + keyword;
      let that = this;
      http({
        url: httpUrl,
        method: "get",
        success(res) {
          if (res.code == 1) {
            let data = res.data.data;
            that.poiList = [];
            for (let i = 0; i < data.length; i++) {
              that.poiList.push({
                //分类ID
                categoryId: data[i].categoryId,
                fid: data[i].fid,
                floorId: data[i].floorId - 1,
                areaId: data[i].areaId,
                poiName: data[i].poiName,
                poiIntro: data[i].poiIntro,
                poiDetail: data[i].poiDetail,
                poiType: data[i].poiType,
                poiStatus: data[i].poiStatus,
                poiIcon: data[i].poiIcon,
                poiImgMoblie: imgUrl + data[i].poiImgMoblie,
                poiImgPc: imgUrl + data[i].poiImgPc,
                //x坐标
                coordinateX: data[i].coordinateX,
                //y坐标
                coordinateY: data[i].coordinateY,
                //距离
                distance: "",
              });
            }

            console.log("requestPoiList2", that.poiList);

            if (kind == "start") {
              routeObj.startPointFlag = true;
            } else if (kind == "end") {
              routeObj.startPointFlag = false;
            }
          }
          map.routeFlag = true;
        },
      });
    },
    requestPoiList3(keyword: string) {
      let that = this;
      http({
        url: interfaceUrl + "poi?keyword=" + keyword,
        method: "get",
        success(res) {
          if (res.code == 1) {
            let data = res.data.data;
            searchObj.resultList = [];
            for (let i = 0; i < data.length; i++) {
              //计算距离
              let sp = { x: that.now.coordinateX, y: that.now.coordinateY };
              let ep = { x: data[i].coordinateX, y: data[i].coordinateY };

              // @ts-ignore
              let dis = fengmap.FMCalculator.distance(sp, ep);

              searchObj.resultList.push({
                //分类ID
                categoryId: data[i].categoryId,
                fid: data[i].fid,
                floorId: data[i].floorId - 1,
                areaId: data[i].areaId,
                poiName: data[i].poiName,
                poiIntro: data[i].poiIntro,
                poiDetail: data[i].poiDetail,
                poiType: data[i].poiType,
                poiStatus: data[i].poiStatus,
                poiIcon: data[i].poiIcon,
                poiImgMoblie: imgUrl + data[i].poiImgMoblie,
                poiImgPc: imgUrl + data[i].poiImgPc,
                //x坐标
                coordinateX: data[i].coordinateX,
                //y坐标
                coordinateY: data[i].coordinateY,
                //距离
                distance: dis.toFixed(0),
              });
            }
            console.log("requestPoiList3", searchObj.resultList);

            searchObj.isShowRes = true;
            let val: PoiInfo = {
              fid: 0,
              coordinateX: 0,
              coordinateY: 0,
              poiName: keyword,
              poiIntro: "",
              floorId: -1,
            };
            searchObj.historyList = searchObj.historyList.slice(0, 9);
            let temp = localStorage.getItem("historyPoiList");
            if (temp) {
              searchObj.historyList = JSON.parse(temp + "");
              if (temp.indexOf(JSON.stringify(val)) == -1) {
                searchObj.historyList.unshift(val);
                localStorage.setItem(
                  "historyPoiList",
                  JSON.stringify(searchObj.historyList)
                );
                console.log(localStorage.getItem("historyPoiList"));
              } else {
                //有搜索记录，删除之前的旧记录，将新搜索值重新push到数组首位
                let i = searchObj.historyList.findIndex((item: any) => {
                  return item.poiName == val.poiName;
                });
                searchObj.historyList.splice(i, 1);
                searchObj.historyList.unshift(val);
                localStorage.setItem(
                  "historyPoiList",
                  JSON.stringify(searchObj.historyList)
                );
              }
            } else {
              searchObj.historyList.unshift(val);
              localStorage.setItem(
                "historyPoiList",
                JSON.stringify(searchObj.historyList)
              );
            }
          }
        },
      });
      // this.requestStatistics("search", {
      //   keyword: keyword,
      // });
    },
    requestStatistics(type: string, data?: object) {
      // 统计
      let uuid = localStorage.getItem("uuid");
      if (!uuid) {
        uuid = this.guid();
        localStorage.setItem("uuid", uuid);
      }
      if (!data) {
        data = {};
      }
      http({
        url: interfaceUrl + "statistics/" + type,
        method: "post",
        data: {
          ...data,
          uuid: uuid,
          ua: navigator.userAgent,
        },
      }).catch((err) => {
        console.log("statistics " + type + " error", err);
      });
    },
    guid() {
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
        var r = (Math.random() * 16) | 0,
          v = c == "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    },
  },
});

export default usePoiStore();
